import { Message } from 'element-ui'
import const_ from 'Plugins/const'
// 
const resultFailureHandler = function (response) {
  let { config, data } = response
  if (config.messageWhenFailure === true || config.messageWhenFailure === undefined) {
    if (const_['ERRORCODE/STATUS'][data.error_code]) {
      requestAnimationFrame(() => {
        Message.error(`${config.desc}失败，原因：${const_['ERRORCODE/STATUS'][data.error_code]}`)
      })
    }
  }
}

const resultSuccessHandler = function (response) {
  let { config } = response
  if (config.messageWhenSuccess === true || (config.messageWhenSuccess === undefined && ['post', 'put', 'delete'].includes(config.method))) {
    Message.success(`${config.desc}成功`)
  }
}

const responseSuccessHandler = function responseSuccessFunc (response) {
  let { data } = response
  if (data.result === 'failure') {
    resultFailureHandler(response)
  }
  if (data.result === 'success') {
    resultSuccessHandler(response)
  }
  return Promise.resolve(response)
}

const responseFailHandler = function (err) {
  const { message, config } = err
  let reason
  if (message && message.indexOf('timeout') !== -1) {
    reason = '请求超时'
  }
  if (message && message.indexOf('code 500') !== -1) {
    reason = '服务器错误'
  }
  if (message && message.indexOf('code 404') !== -1) {
    reason = '接口不存在'
  }
  if (message === 'Network Error') {
    reason = '网络错误'
  }
  Message.error(`${config.desc}失败，原因：${reason}`)
  return Promise.reject(err)
}

export default {
  responseSuccessHandler,
  responseFailHandler
}
